package host.springboot.framework.context.mvc.converter;

import host.springboot.framework.core.constant.PatternConstant;
import host.springboot.framework.core.util.inner.NumberUtils;
import org.jspecify.annotations.NonNull;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * {@code Date} 自定义转换器
 *
 * @author JiYinchuan
 * @since 1.0.0
 */
public class DateConverter implements Converter<String, Date> {

    @Override
    public Date convert(@NonNull String source) {
        try {
            return new SimpleDateFormat(PatternConstant.Date.NORM_DATETIME_PATTERN).parse(source);
        } catch (ParseException e) {
            if (NumberUtils.isParsable(source)) {
                return new Date((Long.parseLong(source)));
            }
            throw new RuntimeException(e);
        }
    }
}
